from zope.interface import implements
from twisted.internet import protocol, reactor
from twisted.web import xmlrpc, server

import os, sys, signal

APPLICATION_INSTALL_DIR = os.environ.get('SIMPLEWATCHER_INSTALL')
if not APPLICATION_INSTALL_DIR:
    raise EnvironmentError("must set environment variable SIMPLEWATCHER_INSTALL")
sys.path.append('%s/lib' % APPLICATION_INSTALL_DIR)


from watcher import WatcherContainer
from watcher.interfaces import IWatch
from watcher.config import ConfigLoader


class WatchProtocol(protocol.ProcessProtocol):
    """watch protocol should really just be a way to
       monitor and communicate with a particular
       run of an executable py script, most commonly
       watch.py.  whatever the executable is, it will
       need to implement the communication standard
       request xml.

       once i determine how the IPC is to be done, I'll 
       implement
         connectionMade
         outReceived
         errReceived
         processEnded
    """
    def __init__(self, name, configPath=None):
        self.config = ConfigLoader(configPath).load(name)
        
    def connectionMade(self):
        self.transport.closeStdin()

    def outReceived(self, data):
        print "stdout from process"
        print data

    def errReceived(self, data):
        print "stderr from process"
        print data

    def processEnded(self, status_object):
        print "process ended with: %s " % status_object.value.exitCode

    def die(self, brutal=False):
        if brutal:
            sig = signal.SIGKILL
        try:
            os.kill(self.transport.pid, sig)
        except:
            os.kill(self.transport.pid, signal.SIGKILL)
